<template>
  <div>
    <el-button type="danger" :icon="Plus" style="float: left; margin-left: 10px" @click="result">新增</el-button>&emsp;
    <el-button type="danger" :icon="Check" style="float: left; margin-left: 10px" @click="save()">保存</el-button>&emsp;
    <el-button type="danger" :icon="Back" style="float: left; margin-left: 10px"
      @click="delDomain()">撤销</el-button>&emsp;
    <el-button type="danger" :icon="Delete" style="float: left; margin-left: 10px" @click="DeleteLoge()">删除</el-button>
  </div>
  <br />
  <div>
    <span style="font-weight: bold"> 负责人: </span>&emsp;
    <el-select v-model="form.Leader" placeholder="-- --" style="width: 240px">
      <el-option label="罗翔" value="罗翔" />
      <el-option label="杨家霖" value="杨家霖" />
      <el-option label="雷鑫" value="雷鑫" />
      <el-option label="王蛋青" value="王蛋青" />
      <el-option label="温媛媛" value="温媛媛" />
      <el-option label="杨杰" value="杨杰" />
      <el-option label="赵丽" value="赵丽" />
      <el-option label="黄强" value="黄强" />
      <el-option label="吴敏" value="吴敏" />
      <el-option label="周亮" value="周亮" />
      <el-option label="徐蕾" value="徐蕾" />
      <el-option label="孙伟" value="孙伟" />
      <el-option label="李霞" value="李霞" />
      <el-option label="马超" value="马超" />
      <el-option label="郭丽" value="郭丽" />
      <el-option label="高峰" value="高峰" />
      <el-option label="何敏" value="何敏" />
      <el-option label="林静" value="林静" />
      <el-option label="罗文" value="罗文" />
      <el-option label="蒋娜" value="蒋娜" />
    </el-select>
    <span style="font-weight: bold"> 转种日期:</span>&emsp;
    <el-date-picker v-model="form.MotherData" type="date" style="width: 200px; border: none"
      placeholder="日期" />&emsp;&emsp; <span style="font-weight: bold"> 单据号: </span>&emsp;
    <el-input style="width: 200px" v-model="form.DocumentNo" placeholder="-- --" />
    <span style="font-weight: bold"> 流水号: </span>&emsp;
    <el-input style="width: 200px" v-model="form.SerialNo" placeholder="-- --" />
  </div>
  <br />
  <hr style="font-size: 20px" />
  <br />

  <div class="table-container" style="height: 400px; position: relative">
    <table style="border-collapse: collapse">
      <tr>
        <td>序号</td>
        <td>耳号</td>
        <td>妊振天数</td>
        <td>分娩难易</td>
        <td>肥羊批次</td>
        <td>母性</td>
        <td>泌乳</td>
        <td>乳房炎</td>
        <td>窝号</td>
        <td>键羔数</td>
        <td>弱羔数</td>
        <td>畸形胎</td>
        <td>死胎数</td>
        <td>木乃伊数</td>
        <td>畸胎数</td>
        <td>活羔数</td>
        <td>窝总重（公斤）</td>
        <td>性别</td>
        <td>当前栋舍</td>
        <td>当前栏位</td>
        <td>转入栋舍</td>
        <td>转入栏位</td>
      </tr>
      <tr v-for="(ruleForm, index) in loge.healthArray">
        <td>{{ index + 1 }}</td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.EweID" placeholder="请选择">
            <el-option v-for="item in eweData.filter((x: any) => x.breedStatuId === 6)" :label="item.earNumber"
              :value="item.sleepInforId" @click="getearMsg(index)" />
          </el-select>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.PregnancyDays"></el-input>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.DeliveryEase" placeholder="请选择">
            <el-option v-for="item in ParturitionDifficulty" :label="item.parturitionDifficultyName"
              :value="item.parturitionDifficultyId" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.BatchNumber" placeholder="请选择">
            <el-option v-for="item in FatSheepBatch" :label="item.fatSheepBatchName" :value="item.fatSheepBatchId" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.MaternalBehavior" placeholder="请选择">
            <el-option label="1分" :value="1" />
            <el-option label="2分" :value="2" />
            <el-option label="3分" :value="3" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.Lactation" placeholder="请选择">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.Mastitis" placeholder="请选择">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.LitterID"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.HealthyLambsCount"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.WeakLambsCount"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.DeformedLambsCount"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.StillbornLambsCount"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.MummifiedLambsCount"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.MalformedFetusCount"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.LiveLambs"></el-input>
        </td>
        <td>
          <el-input style="width: 100px" v-model="ruleForm.LitterTotalWeight"></el-input>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.Gender" placeholder="请选择">
            <el-option label="公" :value="1" />
            <el-option label="母" :value="2" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.CurrentBarn" placeholder="无数据">
            <el-option v-for="item in Recordcottage" :label="item.cottageName" :value="item.cottagesId" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.CurrentPen" placeholder="无数据">
            <el-option v-for="item in Fields" :label="item.fieIdName" :value="item.fieIdId" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.TransferBarn" placeholder="请选择">
            <el-option v-for="item in Recordcottage2" :label="item.cottageName" :value="item.cottagesId"
              @click="getFields2(ruleForm.TransferBarn, index)" />
          </el-select>
        </td>
        <td>
          <el-select style="width: 100px" v-model="ruleForm.TransferPen" placeholder="请选择">
            <el-option v-for="item in Fields2[index]" :label="item.fieIdName" :value="item.fieIdId" />
          </el-select>
        </td>
      </tr>
    </table>
  </div>
  <div style="bottom: 0; left: 0; width: 100%">
    <hr />
    <el-button link type="danger" :icon="Plus" style="float: left; margin-left: 10px"
      @click="addDomain">增行</el-button>&emsp;
    <el-button link type="danger" :icon="Check" style="float: left; margin-left: 10px"
      @click="delDomain">删行</el-button>&emsp;
    <br />
    <hr />
    <span style="vertical-align: top; width: 5%">&emsp; 备注</span>&emsp;
    <el-input v-model="form.Message" type="textarea" style="width: 85%" />
  </div>
</template>
<script lang="ts" setup>
import { Check, Delete, Plus, Back } from '@element-plus/icons-vue';
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
//调用持久化
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();

//钩子函数
onMounted(() => {
  getParturitionDifficulty(); //分娩难易度
  getFatSheepBatch(); //羔羊批次
  geteweData(); //耳号
  getRecordcottage(); //栋舍
  getserialNumber(); //流水号
  aaaData(); //获取时间信息
});
const loge = reactive({
  healthArray: <any>[
    // 默认的第一行数据
    reactive({
      createId: counterStore.employeeId,
      createTime: new Date(),
      updateId: null,
      updateTime: null,
      deleteId: null,
      deletes: false,
      deleteTime: null,
      examId: null,
      examTime: null,
      motherGivingBirthId: 0,
      leader: '',
      motherData: new Date(),
      eweID: 0,
      pregnancyDays: 0,
      deliveryEase: 0,
      batchNumber: 0,
      maternalBehavior: 0,
      lactation: true,
      mastitis: true,
      litterID: 0,
      healthyLambsCount: 0,
      weakLambsCount: 0,
      deformedLambsCount: 0,
      stillbornLambsCount: 0,
      mummifiedLambsCount: 0,
      malformedFetusCount: 0,
      liveLambs: 0,
      litterTotalWeight: 0,
      gender: 0,
      currentBarn: 0,
      currentPen: 0,
      transferBarn: 0,
      transferPen: 0,
      notes: '',
      documentNo: '',
      serialNo: ''
    })
  ]
});

//增行
const addDomain = () => {
  loge.healthArray.push(
    reactive({
      createId: counterStore.employeeId,
      createTime: new Date(),
      updateId: null,
      updateTime: null,
      deleteId: null,
      deletes: false,
      deleteTime: null,
      examId: null,
      examTime: null,
      motherGivingBirthId: 0,
      leader: form.Leader,
      motherData: form.MotherData,
      eweID: 0,
      pregnancyDays: 0,
      deliveryEase: 0,
      batchNumber: 0,
      maternalBehavior: 0,
      lactation: true,
      mastitis: true,
      litterID: 0,
      healthyLambsCount: 0,
      weakLambsCount: 0,
      deformedLambsCount: 0,
      stillbornLambsCount: 0,
      mummifiedLambsCount: 0,
      malformedFetusCount: 0,
      liveLambs: 0,
      litterTotalWeight: 0,
      gender: 0,
      currentBarn: 0,
      currentPen: 0,
      transferBarn: 0,
      transferPen: 0,
      notes: form.Message,
      documentNo: form.DocumentNo,
      serialNo: form.SerialNo.toString()
    })
  );
  console.log(loge.healthArray);
};

//新增
const result = () => {
  loge.healthArray = [];
  addDomain();
};
const DeleteLoge = () => {
  loge.healthArray = [];
};

//减行撤销
const delDomain = () => {
  loge.healthArray.splice(loge.healthArray.length - 1, 1);
};
//获取羊只信息
const form = reactive({
  Leader: '',
  MotherData: '',
  Message: '',
  DocumentNo: '',
  SerialNo: '',
  BreedStatuId: ''
});
const aaaData = () => {
  let n = new Date();
  // 获取年、月、日
  let year = n.getFullYear();
  let month = (n.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以需要 +1
  let day = n.getDate().toString().padStart(2, '0'); // 保证天数是两位数
  // 拼接成 "YYYYMMDD" 格式
  let dateString = `${year}${month}${day}`;
  form.DocumentNo = dateString;
};
//获取羊只信息
const updates = reactive({
  EweID: '',
  Gender: '',
  CurrentBarn: '',
  CurrentPen: ''
});
//#region
/*------------下拉框------------*/
//获取分娩难易度
const ParturitionDifficulty = ref<any>([]);
const getParturitionDifficulty = () => {
  axios
    .get(
      'http://localhost:5039/api/ProductionManagement/ParturitionDifficultyList'
    )
    .then((res) => {
      ParturitionDifficulty.value = res.data.data;
    });
};
//获取肥羊品种
const FatSheepBatch = ref<any>([]);
const getFatSheepBatch = () => {
  axios
    .get('http://localhost:5039/api/ProductionManagement/FatSheepBatchList')
    .then((res) => {
      FatSheepBatch.value = res.data.data;
    });
};

//获取耳号
const eweData = ref<any>([]);
const geteweData = () => {
  axios
    .get('http://localhost:5039/api/SleepBegin/SelectEarFeMale')
    .then((res) => {
      eweData.value = res.data.data;
      console.log(eweData.value);
    });
};
//获取栋舍
const Recordcottage = ref<any>([]);
const Recordcottage2 = ref<any>([]);
const getRecordcottage = () => {
  axios
    .post('http://localhost:5039/api/Cottages/CottageList', {})
    .then((res) => {
      Recordcottage.value = res.data.data;
      Recordcottage2.value = res.data.data;
    });
};
//获取栏位
const Fields = ref<any>([]);
const Fields2 = ref<any>([]);
const getFields = (id: number) => {
  console.log(id);
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', {
      cottagesId: id,
      pageIndex: 1,
      pageSize: 100000000
    })
    .then((res) => {
      console.log(res.data.data);
      Fields.value = res.data.data;
    });
};
const getFields2 = (id: number, index: any) => {
  Fields2.value[index] = [];
  axios
    .post('http://localhost:5039/api/Cottages/SearchFields', {
      cottagesId: id,
      pageIndex: 1,
      pageSize: 100000000
    })
    .then((res) => {
      Fields2.value[index] = res.data.data;
      loge.healthArray[index].TransferPen = '';
      console.log(Fields2.value);
    });
};
//#region 耳号反填

//通过耳号和状态获取妊娠 的信息
const getearMsg = (index: any) => {
  const selectedEweID = loge.healthArray[index].EweID; // 获取选中的 EweID
  console.log(selectedEweID);
  axios
    .get('http://localhost:5039/api/ProductionManagement/EarMasList', {
      params: {
        SleepInforId: selectedEweID,
        BreedStatuId: 4
      }
    })
    .then((res) => {
      console.log(res.data.item);
      updates.EweID = res.data.item.sleepInforId;
      updates.Gender = res.data.item.gender;
      updates.CurrentBarn = res.data.item.recordcottageId;
      updates.CurrentPen = res.data.item.fieIdId;
      handleUpdate(); //调用更新数据的方法
    });
};
// 例子：通过表单输入更新数据
const handleUpdate = () => {
  const eweID = updates.EweID; // 假设你从表单获取到的 EweID
  const gender = updates.Gender; // 假设你从表单获取到的 Gender
  const currentBarn = updates.CurrentBarn; // 假设你从表单获取到的 CurrentBarn
  const currentPen = updates.CurrentPen; // 假设你从表单获取到的 CurrentPen
  console.log(eweID, gender, currentBarn, currentPen);
  updateFieldsByEweID(eweID, gender, currentBarn, currentPen);
};
const updateFieldsByEweID = (
  eweID: string,
  gender: string,
  currentBarn: string,
  currentPen: string
) => {
  // 遍历 healthArray 找到 EweID 对应的项并更新
  const healthItem = loge.healthArray.find((item: any) => item.EweID === eweID);

  if (healthItem) {
    healthItem.Gender = gender;
    healthItem.CurrentBarn = currentBarn;
    getFields(healthItem.CurrentBarn);

    healthItem.CurrentPen = currentPen;
  } else {
    console.log(`没有找到EweID为 ${eweID} 的数据`);
  }
};
/*------------流水号------------*/
const getserialNumber = () => {
  axios
    .post('http://localhost:5039/api/ProductionManagement/GetId', {})
    .then((res) => {
      form.SerialNo = res.data;
    });
};

//#endregion

//#region 保存
const save = () => {
  console.log(form.Leader.trim());
  if (form.Leader.trim() === '') {
    ElMessage.error('请补全责任人');
    return;
  }
  var s = form.MotherData;
  if (s.toString().trim() === '') {
    ElMessage.error('请补全转种日期');
    return;
  }

  loge.healthArray.forEach((item: any) => {
    (item.Message = form.Message),
      (item.DocumentNo = form.DocumentNo),
      (item.SerialNo = form.SerialNo.toString()),
      (item.Leader = form.Leader),
      // console.log(JSON.stringify(form.MotherData));
      item.MotherData = form.MotherData
  });
  let obj = {
    motherGivingBirth: loge.healthArray
  };
  axios
    .post(
      'http://localhost:5039/api/ProductionManagement/MotherGivingBirthAdd',
      obj
    )
    .then((res) => {
      if (res.data.code == 0) {
        console.log('保存成功');
        router.push('/Descendants_transferList');
      }
    });
};

//#endregion
</script>

<style scoped>
.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
  border-top: 3px solid red;
  /* 设置顶部边框为3px宽度的红色 */
  padding: 10px;
  text-align: center;
}

/* 设置 td 的样式 */

table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: center;
  font-size: 14px;
  height: 60px;
  width: 150px;
  white-space: nowrap;
  /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
  max-width: 100%;
  overflow-x: auto;
  /* 启用水平滚动 */
  margin: 20px 0;
  /* 设置容器的外边距 */
}

:deep(.el-input__wrapper) {
  box-shadow: none;
  text-align: center;
}

:deep(.el-select__wrapper) {
  box-shadow: none;
}

::v-deep(.center-input .el-input__inner) {
  text-align: center;
}
</style>
